package open.panxiong.shared.util

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import android.media.MediaMetadataRetriever
import android.util.Log
import java.io.File
import java.io.FileOutputStream


/**
 * 生成缩略图
 */
fun generateThumbnail(  // thumbnail
    inputFile: File,
    outputFile: File,
    size: Int = 100,
    quality: Int = 50
): Boolean {
    return try {
        // 生成 bitmap
        val bitmap = BitmapFactory.decodeFile(inputFile.absolutePath)
        // 找到图片的最小边（根据最小边生成正方形缩略图）
        val minLine = bitmap.width.coerceAtMost(bitmap.height)
        // 创建缩略图
        val thumbnailBitmap = Bitmap.createBitmap(minLine, minLine, bitmap.config)
        val canvas = Canvas(thumbnailBitmap)
        val srcRect: Rect = if (bitmap.getWidth() < bitmap.getHeight()) {
            Rect(0, 0, bitmap.getWidth(), bitmap.getWidth())
        } else {
            Rect(0, 0, bitmap.getHeight(), bitmap.getHeight())
        }
        val dstRect = Rect(0, 0, minLine, minLine)
        canvas.drawBitmap(bitmap, srcRect, dstRect, null)
        bitmap.recycle()
        // 下采样压缩
        val scaledBitmap = Bitmap.createScaledBitmap(thumbnailBitmap, size, size, true)
        // 质量压缩
        val fos = FileOutputStream(outputFile)
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos)
            .let { state ->
                Log.d("缩略图压缩结果", "path:${outputFile.absolutePath} state:$state")
            }
        thumbnailBitmap.recycle()
        fos.flush()
        fos.close()
        true
    } catch (e: Exception) {
        false
    }
}

fun generateCover(
    file: File, coverFile: File,
    size: Int = 100,
    quality: Int = 50
): Boolean {
    val retriever = MediaMetadataRetriever()
    try {
        // 设置视频文件路径
        retriever.setDataSource(file.absolutePath)
        // 获取视频的第一帧图像
        val bitmap = retriever.getFrameAtTime(20) ?: return false
        // 找到图片的最小边（根据最小边生成正方形缩略图）
        val minLine = bitmap.width.coerceAtMost(bitmap.height)
        // 创建缩略图
        val thumbnailBitmap = Bitmap.createBitmap(minLine, minLine, bitmap.config)
        val canvas = Canvas(thumbnailBitmap)
        val srcRect: Rect = if (bitmap.getWidth() < bitmap.getHeight()) {
            Rect(0, 0, bitmap.getWidth(), bitmap.getWidth())
        } else {
            Rect(0, 0, bitmap.getHeight(), bitmap.getHeight())
        }
        val dstRect = Rect(0, 0, minLine, minLine)
        canvas.drawBitmap(bitmap, srcRect, dstRect, null)
        bitmap.recycle()
        // 下采样压缩
        val scaledBitmap = Bitmap.createScaledBitmap(thumbnailBitmap, size, size, true)
        // 质量压缩
        val fos = FileOutputStream(coverFile)
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos)
            .let { state ->
                Log.d("封面图压缩结果", "path:${coverFile.absolutePath} state:$state")
            }
        thumbnailBitmap.recycle()
        fos.flush()
        fos.close()
        return true
    } catch (e: Exception) {
        return false
    } finally {
        retriever.release() // 释放资源
    }
}

//object BitmapUtil {
//
//    fun generateThumbnail(file: File, size: Int = 300): Bitmap? {
//        try {
//            var fis = FileInputStream(file)
//            val options = BitmapFactory.Options()
//            // 先获取图片边界信息
//            options.inJustDecodeBounds = true
//            BitmapFactory.decodeStream(fis, null, options)
//            fis.close()
//
//            // 计算采样率
//            options.inSampleSize = calculateInSampleSize(options, size, size)
//
//            // 加载图片
//            fis = FileInputStream(file)
//            options.inJustDecodeBounds = false
//            var bitmap = BitmapFactory.decodeStream(fis, null, options)
//            fis.close()
//
//            // 检查尺寸并缩放（如果需要）
//            if (bitmap!!.width != size || bitmap.height != size) {
//                bitmap = Bitmap.createScaledBitmap(bitmap, size, size, true)
//            }
//            return bitmap
//        } catch (_: IOException) {
//            return null
//        }
//    }
//
//    private fun calculateInSampleSize(
//        options: BitmapFactory.Options,
//        reqWidth: Int,
//        reqHeight: Int
//    ): Int {
//        val height = options.outHeight
//        val width = options.outWidth
//        var inSampleSize = 1
//
//        if (height > reqHeight || width > reqWidth) {
//            val halfHeight = height / 2
//            val halfWidth = width / 2
//            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
//                inSampleSize *= 2
//            }
//        }
//        return inSampleSize
//    }
//
//    fun drawableToBitmap(drawable: Drawable): Bitmap {
//        // 创建一个可修改的Drawable副本
//        val mutableDrawable = drawable.mutate()
//        // 获取Drawable的尺寸
//        val bitmap = Bitmap.createBitmap(
//            mutableDrawable.intrinsicWidth,
//            mutableDrawable.intrinsicHeight,
//            Bitmap.Config.ARGB_8888
//        )
//        // 创建画布
//        val canvas = android.graphics.Canvas(bitmap)
//        // 将Drawable绘制到画布上
//        mutableDrawable.setBounds(0, 0, canvas.width, canvas.height)
//        mutableDrawable.draw(canvas)
//        // 返回Bitmap对象
//        return bitmap
//    }
//}